package com.yx.muchdatasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author: yaoxin
 * @Date: 2022/3/8 - 03 - 08 - 16:36
 * @Description: com.yx.muchdatasource.config
 * @version: 1.0
 */
@Configuration
@MapperScan(value = "com.yx.muchdatasource.one",sqlSessionFactoryRef = "sqlSessionFactoryBean1")//指定所以包的Mapper接口采用sqlSessionFactoryBean1
public class MyBatisConfigOne {
    @Autowired
    @Qualifier("dsOne")
    DataSource dsOne;

    /**
     * 创建SqlSessionFactory的实例，同时将指定的DataSource实例设置给SqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionFactory sqlSessionFactoryBean1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dsOne);
        return factoryBean.getObject();
    }


    /**
     * SqlSessionTemplate是一个线程安全类，主要用来管理Mybatis中的sqlSession
     * @return
     * @throws Exception
     */
    @Bean
    SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryBean1());
    }
}
